package com.zhiban.project.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import dinamica.Config;
import dinamica.GenericTableManager;
import dinamica.Recordset;
import dinamica.StringUtil;
import dinamica.xml.Document;

public class UploadAttachFile extends GenericTableManager {
	public UploadAttachFile() {
	}

	public int service(Recordset inputParams) throws Throwable {
		if (inputParams.isNull("file.filename"))
			throw new Throwable("文件不能为空!");
		Document doc = getConfig().getDocument();
		String maxSize = doc.getElement("max-size").getValue();
		String filePre = doc.getElement("file-pre").getValue();
		if (filePre == null)
			filePre = "";
		else
			filePre = (new StringBuilder(String.valueOf(filePre))).append("_")
					.toString();
		String fileName = (String) inputParams.getValue("file.filename");
		fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
		fileName = formatRequestEncoding(fileName);
		inputParams.setValue("file.filename", fileName);
		String path = (String) inputParams.getValue("file");
		File f = new File(path);
		Integer size = new Integer((int) f.length());
		inputParams.setValue("file_size", size);
		if (size.intValue() == 0)
			throw new Throwable("文件大小为0!");
		Integer maxSizeVal = Integer.valueOf(Integer.parseInt(maxSize));
		if (size.intValue() > 0x100000 * maxSizeVal.intValue())
			throw new Throwable((new StringBuilder("文件大小限制为最大"))
					.append(maxSizeVal).append("M,您的文件较大，不能提交。").toString());
		Date d = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
		SimpleDateFormat df_year = new SimpleDateFormat("yyyy");
		SimpleDateFormat df_month = new SimpleDateFormat("MM");
		SimpleDateFormat df_date = new SimpleDateFormat("dd");
		SimpleDateFormat df_hour = new SimpleDateFormat("HH");
		String timestamp = df.format(d);
		String directory_year = df_year.format(d);
		String directory_month = df_month.format(d);
		String directory_date = df_date.format(d);
		String directory_hour = df_hour.format(d);
		filePre = (new StringBuilder(String.valueOf(fileName.substring(0,
				fileName.lastIndexOf("."))))).append(filePre).toString();
		String filePathName = (new StringBuilder(String.valueOf(filePre)))
				.append("_")
				.append(timestamp)
				.append(fileName.substring(fileName.lastIndexOf("."),
						fileName.length())).toString();
		String localDir = getContext().getInitParameter("upload-dir");
		localDir = getSpecificOutputPath(localDir);
		localDir = StringUtil.replace(localDir, "${year}", directory_year);
		localDir = StringUtil.replace(localDir, "${month}", directory_month);
		localDir = StringUtil.replace(localDir, "${date}", directory_date);
		localDir = StringUtil.replace(localDir, "${hour}", directory_hour);
		File file = new File(localDir);
		if (!file.exists()) {
			file.mkdirs();
			file = null;
		}
		if (!localDir.endsWith(File.separator))
			localDir = (new StringBuilder(String.valueOf(localDir))).append(
					File.separator).toString();
		String fileLocalPath = (new StringBuilder(String.valueOf(localDir)))
				.append(filePathName).toString();
		inputParams.setValue("file.path", fileLocalPath);
		byte b[] = new byte[0x100000];
		int nRead = 0;
		BufferedInputStream bis = new BufferedInputStream(
				new FileInputStream(f));
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(fileLocalPath));
		while ((nRead = bis.read(b)) != -1)
			bos.write(b, 0, nRead);
		bos.flush();
		bis.close();
		bos.close();
		f.delete();
		String insert = getSQL(getResource("insert.sql"), inputParams);
		getDb().exec(insert);
		publish("result", inputParams);
		int rc = super.service(inputParams);
		return rc;
	}

	protected String formatRequestEncoding(String str) throws Throwable {
		Config _config = getConfig();
		String encoding = getContext().getInitParameter("request-encoding");
		if (encoding != null && encoding.trim().equals(""))
			encoding = null;
		if (_config.requestEncoding != null)
			return new String(str.getBytes("ISO8859-1"),
					_config.requestEncoding);
		if (encoding != null)
			return new String(str.getBytes("ISO8859-1"), encoding);
		else
			return str;
	}

	public static String getSpecificOutputPath(String root) {
		Calendar c = Calendar.getInstance(Locale.CHINA);
		return (new StringBuilder(String.valueOf(root))).append("/")
				.append(c.get(1)).append("/").append(c.get(2) + 1).append("/")
				.append(c.get(5)).append("/").append(c.get(11)).toString();
	}
}
